#include "cgic.h"
#include <glib.h>
#include "MsgUtil.h"
#include "golbal.h"

int cgiMain() {

    //1.解析请求内容 
    char gatewayIp[128];//记录网关ip
    char location[128]; //记录本地的部署位置

    cgiFormString("gatewayIp",gatewayIp,128);
    cgiFormString("location",location,128);

    //把数据存储到文件中：glib
    GKeyFile *keyFile= g_key_file_new();
    //加载文件读取配置文件存储位置
    if(!g_key_file_load_from_file(keyFile,"./config.ini",G_KEY_FILE_NONE,NULL)){
        g_warning("load config.ini error!");
        return -1;

    }
    //读取里面的路径
    gchar *path = g_key_file_get_string(keyFile,"config","devinfo_path",NULL);

    GKeyFile *devFile= g_key_file_new();
    g_key_file_set_string(devFile,"config","gatewayIp",gatewayIp);
    g_key_file_set_string(devFile,"config","location",location);
    g_key_file_save_to_file(devFile,path,NULL);
    g_key_file_free(devFile);
    g_key_file_free(keyFile);
    //1.通过进程通讯 通知 另外一个心跳进程--可以去向服务器注册广告机
    //获取mqId
    int mqId = getMsgQueue(PATHNAME_BOA_MAIN,PROCESS_ID_BOA_MAIN);

    //发送消息
    Message msg ={
        .type =1,
        .text = "register ads"      
    };
    int res =  sendMsg(mqId,&msg,strlen(msg.text)+1);
    if (res==-1)
    {
        cgiHeaderContentType("text/html");	
        fprintf(cgiOut, "<HTML><HEAD> <meta charset=\"UTF-8\"> \n");
        fprintf(cgiOut, "<TITLE>cgic test</TITLE></HEAD>\n");
        fprintf(cgiOut, "<BODY><H1>配置失败</H1>\n");
        fprintf(cgiOut, "</BODY></HTML>\n");
        return -1;
    }
    
    cgiHeaderContentType("text/html");	
	fprintf(cgiOut, "<HTML><HEAD> <meta charset=\"UTF-8\"> \n");
	fprintf(cgiOut, "<TITLE>cgic test</TITLE></HEAD>\n");
	fprintf(cgiOut, "<BODY><H1>操作成功</H1>\n");
    fprintf(cgiOut, "</BODY></HTML>\n");
    return 0;
}